package com.xiaomaoguai.fcp.pre.kepler.ons.configuration;

import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @fileName: OnsAutoConfiguration.java
 * @author: WeiHui
 * @date: 2019/2/26 20:34
 * @version: v1.0.0
 * @since JDK 1.8
 */
@Configuration
@EnableConfigurationProperties(OnsProperties.class)
public class OnsAutoConfiguration {

	@Bean
	public Producer initProducer(OnsProperties onsProperties) {
		String groupId = onsProperties.getGroupId();
		String accessKey = onsProperties.getAccessKey();
		String secretKey = onsProperties.getSecretKey();
		String onsAddr = onsProperties.getOnsAddr();
		if (StringUtils.isEmpty(groupId)
				|| StringUtils.isEmpty(onsAddr)
				|| StringUtils.isEmpty(accessKey)
				|| StringUtils.isEmpty(secretKey)) {
			throw new IllegalArgumentException("需要groupId、onsAddr、accessKey、secretKey信息");
		}
		Properties properties = new Properties();
		properties.put(PropertyKeyConst.GROUP_ID, groupId);
		properties.put(PropertyKeyConst.AccessKey, accessKey);
		properties.put(PropertyKeyConst.SecretKey, secretKey);
		properties.put(PropertyKeyConst.ONSAddr, onsAddr);
		Producer producer = ONSFactory.createProducer(properties);
		producer.start();
		return producer;
	}

}
